/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.log.http;

import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;

import com.commons.core.constant.StringPool;
import com.commons.log.domain.RecordableHttpResponse;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 可记录的 HTTP 响应信息适配器
 */
public final class RecordableServletHttpResponse implements RecordableHttpResponse {

    private final HttpServletResponse response;

    private final int status;

    public RecordableServletHttpResponse(HttpServletResponse response, int status) {
        this.response = response;
        this.status = status;
    }

    @Override
    public int getStatus() {
        return this.status;
    }

    @Override
    public Map<String, String> getHeaders() {
        Map<String, String> headerMap = new HashMap();
        final Collection<String> headerNames = response.getHeaderNames();
        for (String name : headerNames) {
            headerMap.put(name, response.getHeader(name));
        }
        return headerMap;
    }

    @Override
    public String getParams() {
        ContentCachingResponseWrapper wrapper =
            WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        if (null != wrapper) {
            return StringUtils.toEncodedString(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
        }
        return StringPool.EMPTY;
    }
}
